import { api } from "$lib/api"
import { fail, redirect } from "@sveltejs/kit";
import type { Actions, PageServerLoad } from "./$types";
import type { Todo } from "$lib/types/todo";

export const load: PageServerLoad = async ({ url }) => {
    let active: boolean = url.searchParams.get("active") === 'false' ? false : true;

    const todos: Todo[] = await api.get("todos", {
        active,
    });

    return {
        todos,
        active,
    }
}

export const actions = {
    create: async ({ request }) => {
        const data = await request.formData();
        const title = data.get("title");

        if (typeof title === 'string' && title.trim().length === 0) {
            return fail(400, { error: "Title is empty" });
        }

        await api.post("todos", {
            title,
        })

        return { success: true };
    },

    search: async ({ request }) => {
        const data = await request.formData();
        const active = data.get("active");

        await api.get("todos", { active })

        return { success: true };
    },

    finish: async ({ request }) => {
        const data = await request.formData();
        const id = data.get("Id");

        await api.put(`todos/${id}`, { active: false });

        redirect(301, "/");
    }
} satisfies Actions;